package br.ufmg.ubicomp.droidguide.application;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import br.ufmg.ubicomp.droidguide.R;
import br.ufmg.ubicomp.droidguide.eventservice.NotificationList;
import br.ufmg.ubicomp.droidguide.eventservice.ServiceList;
import br.ufmg.ubicomp.droidguide.eventservice.UserEventHandlingService;
import br.ufmg.ubicomp.droidguide.utils.AndroidUtils;

public class Info extends ListActivity {

	List<String> infoItems = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.info);
		initListInfoServices();

		// Use an existing ListAdapter that will map an array
		// of strings to TextViews
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_expandable_list_item_1, infoItems));

		getListView().setItemsCanFocus(true);
		getListView().setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long id) {
				String info = getItem((int) id);
				//showAlert(id, info);
				showInfoView(info);
			}

		});
		getListView().setTextFilterEnabled(true);
	}

	private void initListInfoServices() {
		String[] meuArray = getResources().getStringArray(R.array.info_menu);
		for (String s : meuArray) {
			infoItems.add(s);
		}
	}

	private String getItem(int id) {
		return infoItems.get(id);
	}

	private void showInfoView(String info) {
		if (info.equals("Notifications")) {
			
			AndroidUtils.runTask(new Thread(){
				@Override
				public void run() {
					Context context = getApplicationContext();
					AndroidUtils.showAlert(context, "Updating events . . .");
					try {
						UserEventHandlingService.getInstance().sendEventsToServer();
					} catch (Exception e) {
						e.printStackTrace();
						AndroidUtils.notifyError(e, context, "SendEventsToServer", "UserEventProcessingService");
					}
				}
			}, 0);
			
			AndroidUtils.startActivity(this, NotificationList.class);
		} else if (info.equals("Services")) {
			// start services list
			AndroidUtils.startActivity(this, ServiceList.class);
		} else if (info.equals("Google Search")) {
			WebView wv = AndroidUtils.getWebView(this, R.id.web,
					"http://www.google.com.br");
			AndroidUtils.startActivity(this, Web.class);
		} else if (info.equals("Activities")) {
			AndroidUtils.startActivity(this, TouristActivities.class);
		}
	}
}
